import Vue from "vue";
import Router from "vue-router";
import routes from "./routes.js";
import { getToken } from "../assets/js/auth.js";
import { judgeLink } from "../assets/js/utils.js";
import store from "../store";
Vue.use(Router);

const createRouter = () =>
  new Router({
    // mode: "history", // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes
  });

const router = createRouter();

export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}
router.beforeEach((to, from, next) => {
  let token = getToken();
  if (to.meta.title) {
    document.title = "快速开发技术中台-" + to.meta.title;
  } else {
    document.title = "快速开发技术中台";
  }
  // 系统间跳转 传递token
  if (to.query.token && to.query.token != 1) {
    token = to.query.token;
    // console.log(token);
    localStorage.setItem("token", to.query.token);
    localStorage.setItem("loginName", to.query.username);
    store.commit("user/SET_TOKEN", to.query.token);
    store.commit("user/SET_NAME", to.query.username);
    return next(to.path);
  }
  // // 无token直接跳转登录页
  if (!token && to.path != "/login") {
    return next("/login");
  }

  // 路由验证权限
  if (!judgeLink(to, next)) {
    return;
  }

  next();
});

const routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error);
};

export default router;
